using System;
using OneDayModel.Interfaces;
using OneDayModel.Model;
using OneDayModel.PresentationLogic;

namespace OneDayModel.PresentationLogic
{
    public class UserLoginException : ApplicationException
    {
        public UserLoginException(string message) : base(message) { }
    }

    public class UserLoginUILogic
    {
        private readonly IUserLoginUI userLoginUI;
        private readonly UserLoginModel userLoginModel;

        public UserLoginUILogic(IUserLoginUI userLoginUI, UserLoginModel userLoginModel)
        {
            this.userLoginUI = userLoginUI;
            this.userLoginModel = userLoginModel;

            this.userLoginUI.onUserLogin += userLoginUI_onUserLogin;
        }

        void userLoginUI_onUserLogin(object sender, UserLoginArgs e)
        {
            if (string.IsNullOrEmpty(e.Alias))
            {
                userLoginUI.AliasIsEmpty();
                throw new UserLoginException("Alias is empty");
            }

//            if (string.IsNullOrEmpty(e.Password))
//                throw new UserLoginException("Password is empty");

            IUser user = userLoginModel.GetUserByAlias(e.Alias);
            if (user == null)
            {
                userLoginUI.ShowUserNotFound();
                throw new UserLoginException("User not registered");
            }

            if (user["Password"] != e.Password)
            {
                userLoginUI.ShowInvalidPassword();
                throw new UserLoginException("Invalid Password");
            }

            AccountStatus accountStatus = (AccountStatus) Enum.Parse(typeof(AccountStatus), user["AccountStatus"]);
            switch (accountStatus)
            {
                case AccountStatus.existAndActive:
                    userLoginModel.MarkOnline(user);
                    userLoginUI.ShowUserStartupPage(user);
                    break;

                case AccountStatus.existAndWaitingForConfirmation:
                    userLoginUI.ShowStillWaitingForConfirmation(user);
                    break;
                case AccountStatus.existAndBanned:
                    userLoginUI.ShowAccountBannedPage(user);
                    break;
            }
        }
    }
}